<script setup>
import { reactive, ref, watch } from 'vue'
import ProductSelectDialog from '@/components/ProductSelectDialog.vue'
import { queryProductEcho } from '@/service/product.js'
import { ElMessage } from 'element-plus'
import { addShortDatedProduct, updateShortDatedProduct } from '@/service/shortDatedProduct.js'
import dayjs from 'dayjs'
const props = defineProps({
  type: { type: String, required: true },
})
const emit = defineEmits(['update'])
const showModal = ref(false)
const dialogForm = reactive({
  manufacturingDate: null,
  expiryDate: null,
  productInfo: null,
})
const productSelectDialog = ref()

function validForm() {
  if (dialogForm.productInfo === null) {
    ElMessage.error('请选择临期商品！')
    return false
  }
  if (!dialogForm.manufacturingDate) {
    ElMessage.error('请选择生产日期！')
    return false
  }
  if (!dialogForm.expiryDate) {
    ElMessage.error('请选择过期时间！')
    return false
  }
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  if (dialogForm.expiryDate <= dialogForm.manufacturingDate) {
    ElMessage.error('过期时间不能早于或等于生产日期！')
    return false
  }
  if (dialogForm.manufacturingDate > today) {
    ElMessage.error('生产日期不能是未来日期！')
    return false
  }
  const size = dialogForm.productInfo.productSpecifications.length
  for (let i = 0; i < size; i++) {
    if (
      dialogForm.productInfo.productSpecifications[i].promotionalPrice >=
      dialogForm.productInfo.productSpecifications[i].discountPrice
    ) {
      ElMessage.error(`请设置第${i + 1}个规格的促销价格！`)
      return false
    }
  }
  return true
}

async function onTapSaveButton() {
  if (!validForm()) return
  const params = {}
  params.productId = dialogForm.productInfo.productId
  params.manufacturingDate = dayjs(dialogForm.manufacturingDate).format('YYYY-MM-DD')
  params.expiryDate = dayjs(dialogForm.expiryDate).format('YYYY-MM-DD')
  params.specifications = dialogForm.productInfo.productSpecifications.map((item) => {
    return {
      productSpecificationId: item.productSpecificationId,
      promotionalPrice: item.promotionalPrice,
      stock: item.stock,
    }
  })
  await addShortDatedProduct(params)
  ElMessage.success('成功添加商品！')
  showModal.value = false
  emit('update')
}
async function onTapUpdateButton() {
  if (!validForm()) return
  const params = {}
  params.productId = dialogForm.productInfo.productId
  params.manufacturingDate = dayjs(dialogForm.manufacturingDate).format('YYYY-MM-DD')
  params.expiryDate = dayjs(dialogForm.expiryDate).format('YYYY-MM-DD')
  params.specifications = dialogForm.productInfo.productSpecifications.map((item) => {
    return {
      productSpecificationId: item.productSpecificationId,
      promotionalPrice: item.promotionalPrice,
      stock: item.stock,
    }
  })
  await updateShortDatedProduct(params)
  ElMessage.success('成功更新商品！')
  showModal.value = false
  emit('update')
}

async function handleProductSelectEvent(event) {
  const productId = event[0].id
  const res = await queryProductEcho(productId)
  dialogForm.productInfo = res.data
  dialogForm.manufacturingDate = res.data.manufacturingDate ? new Date(res.data.manufacturingDate) : null
  dialogForm.expiryDate = res.data.expiryDate ? new Date(res.data.expiryDate) : null
}
watch(showModal, (val) => {
  if (!val) {
    Object.assign(dialogForm, {
      manufacturingDate: null,
      expiryDate: null,
      productInfo: null,
    })
  }
})

defineExpose({
  showModal,
  dialogForm,
})
</script>

<template>
  <el-dialog v-model="showModal" :title="type === 'add' ? '新增临期商品' : '编辑临期商品'" draggable width="1300">
    <el-form :model="dialogForm" label-position="right">
      <el-form-item label="临期商品:">
        <template v-if="dialogForm.productInfo && Object.keys(dialogForm.productInfo).length">
          <el-table
            :data="dialogForm.productInfo.productSpecifications"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
            border
            style="width: 100%"
          >
            <el-table-column header-align="center" label="商品信息">
              <template #default="scope">
                <div class="product-info">
                  <img :src="scope.row.productSpecificationImage" alt="" />
                  <div class="product-name">{{ dialogForm.productInfo.productName }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="规格">
              <template #default="scope">
                <div style="font-size: 12px">
                  {{ scope.row.productSpecificationName }}
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="商品价格">
              <template #default="scope">
                <el-input-number v-model="scope.row.discountPrice" :controls="false" disabled>
                  <template #prefix>
                    <span>￥</span>
                  </template>
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column align="center" label="优惠价格">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.promotionalPrice"
                  :controls="false"
                  :max="scope.row.discountPrice"
                  :min="0.01"
                  :precision="2"
                  value-on-clear="max"
                >
                  <template #prefix>
                    <span>￥</span>
                  </template>
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column align="center" label="库存">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.stock"
                  :controls="false"
                  :min="1"
                  :precision="0"
                  value-on-clear="min"
                >
                </el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <template v-else>
          <el-button type="primary" @click="productSelectDialog.showProductSelectDialog = true">点击选择商品</el-button>
        </template>
      </el-form-item>
      <el-form-item label="生产日期:">
        <el-date-picker v-model="dialogForm.manufacturingDate" placeholder="请选择生产日期" type="date" />
      </el-form-item>
      <el-form-item label="过期时间:">
        <el-date-picker v-model="dialogForm.expiryDate" placeholder="请选择过期时间" type="date" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button v-if="type === 'add'" type="primary" @click="onTapSaveButton">保存</el-button>
      <el-button v-if="type === 'edit'" type="primary" @click="onTapUpdateButton"> 更新 </el-button>
      <el-button type="default" @click="showModal = false"> 取消 </el-button>
    </template>
  </el-dialog>

  <product-select-dialog
    ref="productSelectDialog"
    :product-type="0"
    type="radio"
    @on-tap-confirm-product="handleProductSelectEvent($event)"
  ></product-select-dialog>
</template>

<style lang="scss" scoped>
.product-info {
  display: flex;
  align-items: center;
  img {
    width: 60px;
    height: 60px;
  }
  .product-name {
    margin-left: 10px;
    font-size: 12px;
    text-align: left;
    line-height: 15px;
  }
}
</style>
